package com.oracle.malldemo.servlet.order;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.oracle.malldemo.domain.Users;
import com.oracle.malldemo.view.Cart;
import com.oracle.malldemo.view.JsonData;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

@WebServlet(value="/order")
public class SaveOrderServlet extends OrderServlet{

    //保存订单动作只接受post请求

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/plain;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        try {
            //获得json字符串，json字符串-》json对象-》Java对象
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (ServletInputStream) req.getInputStream(), "utf-8"));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            System.out.println(sb);

            //字符串转换json对象。
            //JSONObject jsonObject = JSONUtil.parseObj(sb.toString());
            JSONObject jsonObject = JSONObject.parseObject(sb.toString());
            Cart cart = JSON.parseObject(jsonObject.toJSONString(), Cart.class);
            System.out.println("你的购物车对象是");
            System.out.println(cart);
            String oid = orderMainService.saveOrder(cart);
            if(!"-1".equals(oid)){
                JsonData result = JsonData.success("订单生成成功！",oid);
                out.write(JSONObject.toJSONString(result));
            }
            out.flush();
            out.close();

        } catch (Exception ex) {
            ex.printStackTrace();
            JsonData result = JsonData.fail("订单生成失败！");
            out.write(JSONObject.toJSONString(result));
            out.flush();
            out.close();
        }
    }
}
